package com.lipaluma.test.db.internal.loadData;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Comparator;

import javax.sql.DataSource;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lipaluma.test.db.annotations.LoadDataInfile;
import com.lipaluma.test.db.exceptions.DBTestIllegalUseException;
import com.lipaluma.test.db.internal.Context;
import com.lipaluma.test.db.internal.DbUtils;
import com.lipaluma.test.db.internal.DialectEnum;

public class LoadDataUtils {
	private static Logger LOG = LoggerFactory.getLogger(LoadDataUtils.class);

	public static void doLoadDataInfile(LoadDataInfile.List loadData) throws SQLException, IOException, FileNotFoundException {
		if(loadData != null) {
			LoadDataInfile[] value = loadData.value();
			for (LoadDataInfile loadDataInfile : value) {
				doLoadDataInfile(loadDataInfile);
			}
		}
	}

	public static void doLoadDataInfile(LoadDataInfile loadData) throws SQLException, IOException, FileNotFoundException {
		if (loadData != null) {
			String path = loadData.value();
			if (StringUtils.isBlank(path))
				throw new DBTestIllegalUseException("The folder location must be initialized.");
			File folder = getFolderData(path);
			DataSource ds = getDataSource(loadData.dataSource());
			File[] dataFiles = folder.listFiles();
			if(ArrayUtils.isEmpty(dataFiles))
				throw new IllegalStateException("The folder "+folder.getAbsolutePath()+" doesn't contain any files to load.");
			Arrays.sort(dataFiles, new Comparator<File>() {
				@Override
				public int compare(File f1, File f2) {
					return FilenameUtils.getExtension(f1.getName()).compareTo(FilenameUtils.getExtension(f2.getName()));
				}
			});
			for (File data : dataFiles) {
				long start = System.currentTimeMillis();
				DialectEnum dialect = DbUtils.getDialect(loadData.dataSource());
				if (dialect == null)
					dialect = loadData.dialect();
				String request = dialect.generateLoadDataInfileRequest(data, LoadDataInfileParams.builder().fromAnnotation(loadData).build());
				executeLoadDataInfile(ds, request);
				LOG.debug("Temps d'exécution du load du fichier "+data.getName()+": "+(System.currentTimeMillis() - start)+" ms");
			}
		}
	}
	
	public static void executeLoadDataInfile(DataSource ds, String request) throws SQLException, IOException {
		Connection connection = ds.getConnection();
		LOG.debug("the request : "+StringEscapeUtils.escapeJava(request));
		PreparedStatement ps = connection.prepareStatement(request);
		try {
			ps.execute();
		} catch (SQLException e) {
			throw(new SQLException("[Error when integrating file during the request : \n"+request+"] : "+e.getMessage(), e));
		} finally {
			connection.close();
		}
	}

	public static File getFolderData(String folder) throws FileNotFoundException {
		File file;
		if (folder.startsWith("classpath:")) {
			URL resource = Context.getTestedClass().getResource(folder.substring("classpath:".length()));
			if(resource == null)
				resource = ClassLoader.getSystemResource(folder.substring("classpath:".length()));
			file = new File(resource.getFile().replaceAll("%20", " "));
		} else {
			file = new File(folder);
		}
		if (!file.exists())
			throw new FileNotFoundException("the folder " + file.getAbsolutePath() + " was not found.");
		return file;
	}

	private static DataSource getDataSource(String dataSourceName) throws IOException {
		DataSource ds;
		if(dataSourceName.isEmpty())
			ds = DbUtils.getDataSource();
		else 
			ds = DbUtils.getDataSourceWithName(dataSourceName);
		return ds;
	}
}
